//
//  main.c
//  C_Function_Pr
//
//  Created by chenyh on 2021/1/19.
//

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define LEN 81
char * s_gets(char * st,int n);
int showmenu(void);
void eatline(void); //

void ToUpper(char *);
void ToLower(char *);
void Transpose(char *);                     //大小写转置
void Dummy(char *);                         //不更改字符串
///函数指针
//V_FP_CHARP指针函数名
typedef void (*V_FP_CHARP)(char *);
void show(V_FP_CHARP fp,char * str);

int main(int argc, const char * argv[]) {
    char line[LEN];
    char copy[LEN];
    V_FP_CHARP arpf[4] = {ToUpper,ToLower,Transpose,Dummy};
    //声明一个函数指针，被指向的函数接受char *类型的参数，无返回值
    puts("Enter a string (empty line to quit):");
    int index;
    while (s_gets(line, LEN) != NULL && line[0] != '\0') {
        index = showmenu();
        while (index >= 0 && index < 4) {
            strcpy(copy, line);     //为show()函数拷贝一份
            show(arpf[index], copy);
            //根据用户的选择,使用选定的函数
            index = showmenu();
        }
        puts("Enter a string (empty line to quit):");
    }
    puts("Bye!");
    return 0;
}
char * s_gets(char * st,int n) {
    char *ret_val;
    char *find;
    ret_val = fgets(st, n, stdin);
    if (ret_val) {
        find = strchr(st, '\n');
        if (find)
            *find = '\0'; //在此处放置一个空字符
        else
            while (getchar() != '\n') {
                continue;; //清理输入行中剩余的字符
            }
    }
    return ret_val;
    
}
//得到命令字符
int showmenu(void) {
    char ans;
    int index = 0;
    puts("Enter menu choice:");
    puts("u) uppercase    l) lowercase");
    puts("t) transposed  case o) original case");
    puts("n) next string");
    
    ans = getchar();        //获取用户的输入
    ans = tolower(ans);     //转换为小写
    eatline();              //清理输入行
    while (strchr("ulton", ans) == NULL) {
        puts("Please enter a u,l,t,o,or n:");
        ans = tolower(getchar());
        eatline();
    }
    
    switch (ans) {
        case 'u': index =  0;
        case 'l': index = 1; break;
        case 't': index = 2; break;
        case 'o': index = 3; break;
    }
    
    return index;
}
void eatline(void) {
    while (getchar() != '\n') {
        continue;
    }
} //
void show(void (*fp)(char *),char * str) {
    
    (*fp)(str); //把用户选定的函数作用于str
    puts(str);//显示结果
    
}
void ToUpper(char * str) {
    while (*str) {
        *str = toupper(*str);
        str++;
    }
}
void ToLower(char * str) {
    while (*str) {
        *str = tolower(*str);
        str++;
    }
}
void Transpose(char * str) {
    while (*str) {
        if (islower(*str)) {
            *str = toupper(*str);
        }else if (isupper(*str)) {
            *str = tolower(*str);
        }
        str++ ;
    }
    
    
}                     //大小写转置
void Dummy(char *str) {
    
}                         //不更改字符串
